package main

import (
	"chapter-04-token-auth/service"
	"chapter-04-token-auth/service/impl"
	"context"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"log"
)

const (
	// Address gRPC服务地址
	Address = "127.0.0.1:8003"
)

func main() {

	user := &impl.Authentication{
		User:     "admin1",
		Password: "admin",
	}
	//1、 建立连接
	conn, err := grpc.Dial(Address, grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithPerRPCCredentials(user))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer func(conn *grpc.ClientConn) {
		err := conn.Close()
		if err != nil {

		}
	}(conn)
	// 2. 调用 hello_grpc.pb.go 中的NewQueryUserClient方法建立客户端
	client := service.NewSayHelloClient(conn)
	hello := funcCallGrpc(err, client)
	if err != nil {
		log.Fatal("调用gRPC方法错误: ", err)
	}
	fmt.Println("Token：调用gRPC方法成功，ProdStock = ", hello)

}

func funcCallGrpc(err error, client service.SayHelloClient) *service.HelloResponse {
	//3、调用rpc方法
	hello, err := client.SayHello(context.Background(), &service.HelloRequest{Id: "1"})
	if err != nil {
		panic(err)
	}
	return hello
}
